﻿using ERPSystem.Common.Domains.Delivergoods;
using ERPSystem.Common.Domains.supplier;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace BasicInformationCommon.API.BasicInformationCommons.Suppliers
{
    public class PurchaseOrderDaoHandler : IRequestHandler<PurchaseOrderDaoCommand, FileExportResult>
    {

        private readonly IBaseRepository<PurchaseOrder> purchaseOrderRepository;

        public PurchaseOrderDaoHandler(IBaseRepository<PurchaseOrder> purchaseOrderRepository)
        {
            this.purchaseOrderRepository = purchaseOrderRepository;
        }

        public async Task<FileExportResult> Handle(PurchaseOrderDaoCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();

            var list = await(await purchaseOrderRepository.GetAll()).ToListAsync();
            Console.WriteLine(list.Count);
            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            IRow row1 = sheet.CreateRow(0);

            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(2).SetCellValue("跟单编号");
            row1.CreateCell(3).SetCellValue("单据状态");
            row1.CreateCell(4).SetCellValue("供应商");
            row1.CreateCell(5).SetCellValue("物料名称");
            row1.CreateCell(6).SetCellValue("物料编码");
            row1.CreateCell(7).SetCellValue("需求日期");
            row1.CreateCell(8).SetCellValue("采购数量");
            row1.CreateCell(9).SetCellValue("单据日期");



            int rowIndex = 0;
            foreach (var item in list)
            {
                row1 = sheet.CreateRow(rowIndex);
                row1.CreateCell(0).SetCellValue(item.PurchaseOrderId);
                row1.CreateCell(2).SetCellValue(item.ReceiptNum);
                row1.CreateCell(3).SetCellValue(item.ReceiptState);
                row1.CreateCell(4).SetCellValue(item.System);
                row1.CreateCell(5).SetCellValue(item.MaterialName);
                row1.CreateCell(6).SetCellValue(item.MaterialCode);
                row1.CreateCell(7).SetCellValue(item.ApprovalDate);
                row1.CreateCell(8).SetCellValue(item.ArrivalQuantity);
                row1.CreateCell(9).SetCellValue(item.ReceiptDate);

                rowIndex++;

            }
            byte[] data = null;
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                data = ms.ToArray();
            }
            string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "发货通知单.xlsx";

            result.FileBytes = data;
            result.MimeType = contextType;
            result.FileName = fileName;
            return result;
        }
    }
}
